package esjd.demo.serivce.impl;

import com.alibaba.fastjson.JSON;
import esjd.demo.pojo.Pordouct;
import esjd.demo.serivce.SerivceIndex;
import esjd.demo.utile.HttpUtile;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class Serivceimplndex implements SerivceIndex {
         @Autowired
         @Qualifier("restHighLevelClient")
         private RestHighLevelClient client;

         private final String INDEX="jd_list";

    /**
     * 向elasticSearch 存储数据
     * @param key
     * @return
     * @throws IOException
     */
    @Override
    public boolean saveList(String key) throws IOException {
        List<Pordouct> list = HttpUtile.getList(key);
        BulkRequest bulkRequest=new BulkRequest();
        for (int i = 0; i <list.size() ; i++) {
           bulkRequest.add(
                   new IndexRequest(INDEX)
                           .source(JSON.toJSONString(list.get(i).toString()),XContentType.JSON)
                   );
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return  !bulk.hasFailures();
    }

    /**
     * 	/**  	查询
     * 	 *     searchRequest 搜索请求
     * 	 *     SearchSourceBuilder 条件构造
     * 	 *     HighlightBuilder 构造高亮
     * 	 *     TermQueryBuilder 精确查询
     * 	 *     xxx QueryBuilder
     * @param key
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<Map<String, Object>> getlist(String key, Integer page, Integer size) throws IOException {
         if (size==null){
             size=20;
         }
        SearchRequest request=new SearchRequest(INDEX);

        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();

        //查询条件 我们可以使用QueryBuilders 工具来 实现
        TermQueryBuilder termQuery = QueryBuilders.termQuery("text", key);
        sourceBuilder.query(termQuery);

         sourceBuilder.from(page);
         sourceBuilder.size(size);

        HighlightBuilder highlightBuilder=new HighlightBuilder();
        //设置高亮字段
        highlightBuilder.field("text");
        highlightBuilder.preTags("<p style='color:red'>");
        highlightBuilder.postTags("</p>");
        sourceBuilder.highlighter(highlightBuilder);

       request.source(sourceBuilder);

        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            //解析高亮的字段
            //获取高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField content = highlightFields.get("text");
            System.out.println("==text=="+content);
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();//原来的结果
            //将原来的字段替换为高亮字段即可
            if (content!=null){
                Text[] fragments = content.fragments();
                String newTitle = "";
                for (Text text : fragments) {
                    newTitle +=text;
                }
                sourceAsMap.put("text",newTitle);//替换掉原来的内容
            }
            list.add(sourceAsMap);
        }
        list.forEach(System.out::println);
        return list;
    }


}
